package classes.Commands
{
	import components.editor.c_baseElement;
	import components.editor.c_bitmapElement;
	import components.editor.c_holeyElement;
	
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	
	public class c_insertInHoleCommand extends c_baseCommand {
		private var _source			: DisplayObject;
		private var _holeElement	: c_holeyElement;
		private var _curHoleIndex	: int;
		
		private var _prevHoleImage	: c_baseElement;
		private var _prevImageIndex	: int;
		private var _prevLink		: c_baseElement;
		
		public function c_insertInHoleCommand(a_holeElement: c_holeyElement, a_source: DisplayObject) {
			super();
			_holeElement 	= a_holeElement;
			_source 		= a_source;
			_curHoleIndex 	= _holeElement.curHole;
		}
		
		protected function doRemoved(e: Event): void {
			_holeElement.getHole(_curHoleIndex).image = null;
			_element.removeEventListener(Event.REMOVED, doRemoved);
		}
		
		override public function Execute():void {
			_prevLink 			= _holeElement.editor.dragRect.link;
			var hole: Object 	= _holeElement.getHole(_curHoleIndex);
			
			if (hole.image) {
				_prevHoleImage 	= hole.image;
				_prevImageIndex	= hole.image.index;
				hole.image.remove();
			}
			if (!_element) { 
				_element 	= new c_bitmapElement(_holeElement.editor.imageLayer, new Rectangle(0, 0, _source.width, _source.height), _source);
				
				var scale	: Number = Math.max(hole.bounds.width/_element.width, hole.bounds.height/_element.height);
				var mat		: Matrix = new Matrix();
				var oc		: Point  = new Point(_element.width / 2, _element.height / 2);
				
				mat.translate(-oc.x, -oc.y);
				mat.scale(scale, scale);
				mat.translate(hole.bounds.x + hole.bounds.width / 2, 
					hole.bounds.y + hole.bounds.height / 2);
				mat.concat(_holeElement.matrix);
				_element.matrix = mat;
			} else {
				_holeElement.parent.addChild(_element);
			}
			
//			hole.mask.visible 	= true;
			_element.mask 		= hole.mask;	
			hole.image 			= _element;
			
			_holeElement.parent.swapChildren(_holeElement, _element);
			_element.owner 	= _holeElement;
			_element.addEvent(Event.REMOVED, doRemoved);
			
			_holeElement.editor.dragRect.link = _element;
		}
		
		override public function unExecute():void {
			_element.remove()
			var hole: Object = _holeElement.getHole(_curHoleIndex);
			hole.image = _prevHoleImage;
			if (_prevHoleImage) {
				_prevHoleImage.setParent(_holeElement.editor.imageLayer, _prevImageIndex);
				_prevHoleImage.mask = hole.mask;
			} else _holeElement.editor.dragRect.link = _prevLink;
		}
		
		override public function dispose():void {
			_element.dispose();
		}			
	}
}